import { Component, ElementRef, OnInit, Input, Output, EventEmitter, ViewChild } from '@angular/core';
import { HttpModule, Headers, RequestOptions, Http } from '@angular/http';
import { HttpClientModule, HttpClient, HttpErrorResponse } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { RouterModule, Router, ActivatedRoute } from '@angular/router';

import { Service } from '../../../server/server';
import { CudTableService } from '../../../public/serve/cud-table/cud-table.service';
import { Data } from '@angular/router/src/config';
declare var $: any;

@Component({
  selector: 'app-institution-add-admin',
  templateUrl: './institution-add-admin.component.html',
})
export class InstitutionAddAdminComponent implements OnInit {

  constructor(private http: Http, private router: Router, public server: Service, private cudTableService: CudTableService, ) { }

  ngOnInit() {
    this.createUserId = this.server.getuser();
    this.server.institutioneventEmit.subscribe((value: any) => {
      this.institutiondate = value;
      //console.log(this.institutiondate)
      this.superiorAdd = this.institutiondate.institutionName;
      this.superiorAddId = this.institutiondate.institutionId;
    });
    this.getTabList();
    this.maxDate = new Date();
  }

  //取消订阅
  public institutioneventEmit: any;
  ngOnDestroy() {
    if (this.institutioneventEmit) {
      this.institutioneventEmit.unsubscribe();
    }
  }

  public maxDate: Data;
  @Output()
  addOutput: EventEmitter<any> = new EventEmitter();

  //发射引导值
  @Output()
  addstepOutput: EventEmitter<any> = new EventEmitter();

  @Input() superiorAdd: any;

  @Input() superiorAddId: any;

  //清空表单
  @ViewChild('FormAdd') formElement: HTMLFormElement

  institutiondate: institutiondates = {};

  createUserId: any;//操作用户

  step: number = 0; //步骤
  stepadds: any;//步骤组装数据

  //验证是否选图片
  public imgActive: any = false;
  ngDoCheck() {
    if ($(".fileinput").hasClass("fileinput-exists")) {
      this.imgActive = true;
    } else {
      this.imgActive = '';
    }
  }

  ngAfterContentInit() {
    this.getTabList();
  }


  //清空选择框方法
  reset() {
    this.getTabList();
    this.formElement.reset();
    $('.fileinput-exists').click();
    setTimeout(() => {
      this.adddate.sex = 1;
      this.adddate.status = true;
      this.adddate.isActivate = true;
      this.adddate.isAutonym = true;
      //this.adddate.roleId = this.roledata[0].roleId;
    }, 300)
  }
  //所属角色
  public roledata: roledatas;
  //初始化数据
  adddate: any = {
    queryType: "1",
    roleId: this.roledata,
    roleName: "",
    userId: "",
    createUserId: this.createUserId,
    lastLoginDate: "",
    createDate: "",
    updatePasswordDate: "",
    institutionId: this.institutiondate.institutionId,
    parentId: this.superiorAddId,
    userName: "",
    displayName: "",
    password: "",
    email: "",
    registerSource: "",
    portrait: "",
    userFolder: "",
    status: true,
    isActivate: true,
    isAutonym: true,
    isSuper: "",
    activateKey: "",
    activateLastDate: "",
    realName: "",		  //真实姓名
    firstName: "",	  //姓
    lastName: "",		  //名
    identityCard: "", //身份证
    phone: "",		    //电话
    mobile: "",		    //手机
    sex: 1,		      //性别
    birthday: "",		  //生日	
    province: "",		  //省份
    city: "",	        //城市
    address: "",		  //地址
    qq: "",		        //qq号
    postCode: "",		  //邮编
    school: "",		    //学校   
    target: "user/person/"
  };

  submitAdd(val, valstep) {
    //console.log(val,valstep)
    //console.log(this.institutiondate.institutionId)
    this.adddate.institutionId = this.institutiondate.institutionId;
    this.adddate.createUserId = this.createUserId;
    val.status = Number(val.status)
    val.isActivate = Number(val.isActivate)
    val.isAutonym = Number(val.isAutonym)
    //转换时间格式
    val.birthday = this.server.formatDate(val.birthday);
    let formData = new FormData();
    for (let key in val) {
      formData.append(key, val[key]);
      val.institutionId = this.institutiondate.institutionId;
      val.target = "user/person/";
    }
    formData.append("imageinfo", $('#picID')[0].files[0] || '');

    let url = this.server.baseUrl + 'admin/pusers/add';
    let headers = new Headers({ 'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryhdymHRIkeSu' });
    let options = new RequestOptions({ headers: headers });
    headers.delete("Content-Type");
    this.http.post(url, formData, options).toPromise().then((res: any) => {
      res = res.json();
      //console.log(res)
      if (res.result_code == '0000') {
        //prompt
        this.server.prompt = { prompt: true, success: true, fail: false, promptStatement: res.message };
        this.server.promptclose;
        this.addOutput.emit(res.result_code);
        this.reset();
        //新增管理员退出
        if (valstep == 0) {
          this.stepadds = { step: 0, treeopp: false }
          this.addstepOutput.emit(this.stepadds);
          $("#adminAdd").modal("hide");
        }
        //新增管理员并添加IP规则
        if (valstep == 1) {
          this.stepadds = { step: 4, treeopp: true, title: "设置IP白名单规则", btn: "下一步" }
          this.addstepOutput.emit(this.stepadds);
          $("#adminAdd").modal("hide");
          setTimeout(() => {
            $("#ipAdd").modal("show");
            this.stepadds = { step: 4, treeopp: false, title: "设置IP白名单规则", btn: "下一步" }
            this.addstepOutput.emit(this.stepadds);
          }, 500)

        }
        //update
      } else {
        this.server.prompt = { prompt: true, success: false, fail: true, promptStatement: res.message };
        this.server.promptclose;
      }
    }).catch()
  }


  // 表格
  getTabList() {
    let url = this.server.baseUrl + 'admin/roles/getRoleDropList';
    this.cudTableService.postRequest(url, {}).then((data: any) => {
      this.roledata = data.result;
      //this.adddate.roleId = this.roledata[0].roleId;
      //console.log(data.result);
      if (this.roledata) {
        this.activerole(this.roledata);
      }

    }).catch();
  }

  //选中
  activerole(arry) {
    for (var i = 0; i < arry.length; i++) {
      if (arry[i].autoAssignment == 1) {
        this.adddate.roleId = arry[i].roleId;
      }
    }
  }

}
export class addDatatype {
  queryType?: string;
  roleId?: string;
  userId?: string;
  createUserId?: string;
  institutionId?: string;
  userName?: string;
  displayName?: string;
  password?: string;
  email?: string;
  registerSource?: string;
  portrait?: string;
  userFolder?: string;
  status?: string;
  isActivate?: string;
  isAutonym?: string;
  parentId?: string;
  lastLoginDate?: string;
  createDate?: string;
  updatePasswordDate?: string;
  roleName?: string;
  isSuper?: string;
  activateKey?: string;
  activateLastDate?: string;
  realName?: string;		//真实姓名
  firstName?: string;	  //姓
  lastName?: string;		//名
  identityCard?: string;	  //身份证
  phone?: string;		//电话
  mobile?: string;		//手机
  sex?: string;		//性别
  birthday?: string;		//生日	
  province?: string;		//省份
  city?: string;   	//城市
  address?: string;		//地址
  qq?: string;		//qq号
  postCode?: string;		//邮编
  school?: string;		//学校
}

export class institutiondates {
  institutionId?: string;
  institutionName?: string;
};

export class roledatas {
  autoAssignment?: number;
  roleId?: string;
  roleName?: string;
}